/**
 * Generate the slider HTML
 */
function slider_prepare() { 

    // Generate Slider Scroller HTML
    jQuery('#slider-scroller').html('<div id="slider-scroller-inner"><div id="slider-scroller-main"></div></div>');

    // Wrap items in main slider with columns
    var slider_slides = jQuery('#slider-main .slider-item');
    for(var i = 0; i < slider_slides.length; i+=2) {
      slider_slides.slice(i, i+2).wrapAll('<div class="slider-col"></div>');
    }
    jQuery('.slider-col:first').addClass('slider-col-first');

    // Add the featured item in the slider (for use by mobile only)
    var featured_mobile_slide_img = jQuery('#slider-featured-thumb img').attr('src');
    var featured_mobile_slide_info = jQuery('#slider-featured-info-title').html();
    var featured_mobile_slide = '<div class="slider-col-mobile"><div class="slider-item"><div class="slider-item-thumb"><img src="' + featured_mobile_slide_img + '" /></div><div class="slider-item-info"><div class="slider-item-title"><span class="slider-item-info-title">' + featured_mobile_slide_info + '</span></div></div></div></div>';
    jQuery('#slider-main-inner').prepend(featured_mobile_slide);
    jQuery('.slider-col-mobile .categoryBadge').prependTo('.slider-col-mobile .slider-item-thumb');

}

/**
 * Initializing Slider
 */
function slider_init() {

    // Call function for generating widths
    slider_widths();

}

/**
 * Generate slider widths
 */
function slider_widths() {

    // Calculate width of the content inside of the slider
    var itemsAmount = jQuery('.slider-col, .slider-col-mobile:visible').length;
    if ( $('.slider-col-mobile:visible').length ) { 
        itemsAmount = itemsAmount - 0.5;   
    }
    var itemWidth = jQuery('.slider-col').outerWidth(true);
    var itemsWidth = itemWidth * itemsAmount;
    var sliderWidth = jQuery('#slider-main').width();    

    // Set the widths
    jQuery('#slider-main-inner, #slider-scroller-main').css( 'width', itemsWidth );
    jQuery('#slider-scroller-inner').css( 'width', sliderWidth);

    // Update scrollbars
    slider_scrollbar_update();

}

/**
 * Initiliaze scrollbar
 */
function slider_scrollbar_init() {

    // Initialize scrollbar on main slider
    jQuery('#slider-main').mCustomScrollbar({
        horizontalScroll: true,
        scrollInertia: 400,
        contentTouchScroll: false,
        callbacks: {

            // Sync with the "fake" scrollbar (the one that's visible on the website)
            whileScrolling: function(response){

                if ( jQuery('#slider').hasClass('slider-scrolling-real') || jQuery('.mCS_touch').length ) {

                    scrollOffset = response.draggerLeft;
                    jQuery('#slider-scroller-inner').mCustomScrollbar( 'scrollTo', scrollOffset, {
                        scrollInertia : 0,
                        moveDragger: 1
                    });

                }

            },

            // When the end is eached load more items
            onTotalScroll: function(){

                if ( ! $('#slider').hasClass('slider-appending') ) {
                    $('#slider').addClass('slider-appending');
                    slider_append_items();
                }

            }
        },
        advanced: {
            autoExpandHorizontalScroll: 1
        }
    });

    // Initialize "fake" scrollbar (the one that's visible on the website)
    jQuery('#slider-scroller-inner').mCustomScrollbar({
        horizontalScroll: true,
        contentTouchScroll: false,
        callbacks: {

            // Sync with the real scrollbar (the one that's invisible on the website)
            whileScrolling: function(response){

                if ( jQuery('#slider').hasClass('slider-scrolling-fake') || jQuery('#slider-scroller .mCSB_dragger').hasClass('mCSB_dragger_onDrag') ) {
                    
                    scrollOffset = response.draggerLeft;
                    jQuery('#slider-main').mCustomScrollbar( 'scrollTo', scrollOffset, {
                        scrollInertia : 0,
                        moveDragger: 1
                    });

                }

            },
            // When the end is reach load more items
            onTotalScroll: function(){
                jQuery('#slider').addClass('.slider-appending');
            }
        }
    });

}

/**
 * Update scrollbar
 */
function slider_scrollbar_update() {

    jQuery('#slider-main, #slider-scroller-inner').mCustomScrollbar('update');
    $('.slider-appending').removeClass('slider-appending');

}

/**
 * Append items to slider
 */
function slider_append_items() {

    // Get random slides from existing ones
    var slides = jQuery('.slider-col');
    var slides_amount = slides.length;
    var slide_random = Math.floor( Math.random() * slides_amount + 1 );
    var slide_copy = slides.eq(slide_random).clone();

    // Add new items
    $('.slider-col:last').after(slide_copy);

    slider_image_load();
    slider_init();

}

/**
 * Images loading
 */
function slider_image_load() {

    jQuery('.slider-item-thumb img').one('load', function() {
        jQuery(this).closest('.slider-item').find('.slider-item-thumb, .slider-item-info').animate({ 'opacity' : 1 }, 500);
    }).each(function() {
        if(this.complete) jQuery(this).load();
    });

    jQuery('#slider-featured-thumb img').one('load', function() {
        jQuery(this).closest('#slider-featured-thumb').animate({ 'opacity' : 1 }, 500);
    }).each(function() {
        if(this.complete) jQuery(this).load();
    });
    
}

/**
 * Center video icon
 */
function slider_center_icon() {
    
    // Declare variables
    var video_icon, video_icon_container, video_info, video_icon_h, video_icon_w, video_icon_container_h, video_icon_container_w, video_icon_offset_h, video_icon_offset_w;

    // Check if exists
    if ( jQuery('.videoIcon').length ) {

        // Handle each separately
        jQuery('.videoIcon').each(function(){

            // Elements
            video_icon = jQuery(this);
            video_icon_container = video_icon.closest('.slider-item');
            video_info = video_icon_container.find('.slider-item-info:visible');
            
            // Icon dimensions
            video_icon_h = video_icon.height();
            video_icon_w = video_icon.width();

            // Container dimensions
            video_icon_container_h = video_icon_container.height() - video_info.outerHeight();
            video_icon_container_w = video_icon_container.width();

            // Offsets
            video_icon_offset_h = video_icon_container_h / 2 - video_icon_h / 2;
            video_icon_offset_w = video_icon_container_w / 2 - video_icon_w / 2;

            // Center
            video_icon.css({ 'top' : video_icon_offset_h, 'left' : video_icon_offset_w });

        });

    }

}

/**
 * When the DOM is ready
 */
jQuery(document).ready(function($) {

    // Prepare HTML and load images
    slider_image_load();

    // Add/remove classes to determine if user is interacting with the slider
    $('#slider-main').live('mouseenter', function(){
        $('#slider').addClass('slider-scrolling-real');
    }).live('mouseleave', function(){
        $('#slider').removeClass('slider-scrolling-real');
    });

    // Add/remove classes to determine if user is interacting with the scrollbar
    $('#slider-scroller').live('mouseenter', function(){
        $('#slider').addClass('slider-scrolling-fake');
    }).live('mouseleave', function(){
        $('#slider').removeClass('slider-scrolling-fake');
    });

    // Swiping functionality for devices that support it
    $("#slider-main").swipe( {
        
        // Left swipe
        swipeLeft: function(event, direction, distance, duration, fingerCount) {

            var curr_pos = $('#slider-main .mCSB_container').position();            
            var scroll_offset = (curr_pos.left - distance) * -1;
            jQuery('#slider-main').mCustomScrollbar( 'scrollTo', scroll_offset );

        },
        // Right swipe
        swipeRight: function(event, direction, distance, duration, fingerCount) {

            var curr_pos = $('#slider-main .mCSB_container').position();            
            var scroll_offset = (curr_pos.left + distance) * -1;
            jQuery('#slider-main').mCustomScrollbar( 'scrollTo', scroll_offset );

        },
        excludedElements: 'button, input, select, textarea, .noSwipe'

    });

});

/**
 * When page completely loads
 */
jQuery(window).load(function(){

    // Initiate slider and scrollbar
    slider_prepare();
    slider_image_load();
    slider_init();
    slider_center_icon();
    slider_scrollbar_init();

    // Reinitiate slider when windows resized (responsivness)
    jQuery(window).resize(function() {
        slider_init();
        slider_center_icon();
    });

});